//
//  ProductLibEditVC.m
//  LazyCat
//
//  Created by jike on 16/5/4.
//  Copyright © 2016年 zhanshu. All rights reserved.
//

#import "ProductLibEditVC.h"
#import "ProductLibManagerCell.h"
#import "classifyViewController.h"
@interface ProductLibEditVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView *_tableView;
    NSString *_shoujiaStr;
    NSString *_chengbenStr;
    NSString *_kucunStr;
    NSMutableArray *_dataArrayTwo;
    UILabel *_catecoryLabel;//分类名显示label
    UIButton *_chooseCateBtn;
    
    NSString *_cname;
    NSString *_cid;
    UILabel *_cnameLabel;//分类名label
    NSString *_pid;
    NSMutableArray *_editArr;
    NSIndexPath *_indexPath;
    UIView * _backTView;
}
@end

@implementation ProductLibEditVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}
- (void)createUI {
    _chengbenStr = @"";
    _shoujiaStr = @"";
    _kucunStr = @"";
    _pid = @"";
    _cid = @"";
    self.view.backgroundColor = BackColor;
    [self initNav:@"批量添加" doBack:YES];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 + 44, ScreenWidth, ScreenHeight - 64 - 44 - 44) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = BackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    
    //
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardshow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardhide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    /**
     导航栏点击去掉键盘
     */
    UIControl * control = [[UIControl alloc]initWithFrame:CGRectMake(70, 20, ScreenWidth - 70, 44)];
    [control addTarget:self action:@selector(hideKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:control];
    
    
    /////类别视图
    UIView *categoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 44)];
    categoryView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:categoryView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
    lineView.backgroundColor = SetColor(0, 0, 0, 0.1);
    [categoryView addSubview:lineView];
    
    UILabel *TitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 , 0, 72, 44)];
    TitleLabel.text = @"商品分类";
    TitleLabel.font = [UIFont systemFontOfSize:14];
    TitleLabel.textColor = SetColor(80, 80, 80, 1);
    [categoryView addSubview:TitleLabel];
    
    UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 43.5, ScreenWidth, 0.5)];
    lineView2.backgroundColor = SetColor(1, 1, 1, 0.2);
    [categoryView addSubview:lineView2];
    
    
    _chooseCateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _chooseCateBtn.frame = CGRectMake(ScreenWidth - 92, 0, 72, 44);
    [_chooseCateBtn setTitle:@"选择分类" forState:UIControlStateNormal];
    [_chooseCateBtn setTitleColor:SetColor(153, 153, 153, 1) forState:UIControlStateNormal];
    _chooseCateBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_chooseCateBtn addTarget:self action:@selector(chooseCategoryBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [categoryView addSubview:_chooseCateBtn];
    
    _catecoryLabel = [[UILabel alloc]initWithFrame:CGRectMake(92, 0, 120, 44)];
    _catecoryLabel.textColor = SetColor(153, 153, 153, 1);
    _catecoryLabel.font = [UIFont systemFontOfSize:14];
    [categoryView addSubview:_catecoryLabel];
    
    UIImageView *inImageV = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 15,15, 7, 13)];
    inImageV.image = [UIImage imageNamed:@"inImagePic"];
    [categoryView addSubview:inImageV];
    
    [self.view addSubview:_tableView];
    
    //保存
    UIView *baocunView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 44, ScreenWidth, 44)];
    baocunView.backgroundColor = MainColorT;
    
    [self.view addSubview:baocunView];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, ScreenWidth, 44);
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(baocunBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [baocunView addSubview:btn];
    
    
    _dataArrayTwo = [NSMutableArray array];
    _editArr = [NSMutableArray array];
    [_dataArrayTwo addObjectsFromArray:_dataArray];
    
    for (NSInteger i = _dataArrayTwo.count - 1; i >= 0; i--) {
        NSDictionary *dic = (NSDictionary *)_dataArrayTwo[i];
        if ([[dic allKeys] containsObject:@"a"]) {
            [_dataArrayTwo removeObjectAtIndex:i];
        }
    }
    NSLog(@"%@",_dataArrayTwo);
    for (int i = 0; i< _dataArrayTwo.count; i++) {
            NSMutableArray *arr = [NSMutableArray array];
            NSString *priceStr = [_dataArrayTwo[i] objectForKey:@"price"];
            NSString *chengbenStr = [_dataArrayTwo[i] objectForKey:@"price"];
            NSString *kuncunStr = [_dataArrayTwo[i] objectForKey:@"dftstock"];
            NSString *pid = [_dataArrayTwo[i] objectForKey:@"prodid"];
            [arr addObject:priceStr];
            [arr addObject:chengbenStr];
            [arr addObject:kuncunStr];
            [arr addObject:pid];
            [_editArr addObject:arr];
//        }
    }
#pragma mark -- 无数据提示
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    if (_editArr.count > 0) {
        _backTView.hidden = YES;
    }else {
        _backTView.hidden = NO;
    }
    UIImageView *noProImV = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-49)/2, 115, 49, 49)];
    noProImV.image = [UIImage imageNamed:@"noOrder"];
    [_backTView addSubview:noProImV];
    
    UILabel *noProMess = [[UILabel alloc]initWithFrame:CGRectMake(0, 170, ScreenWidth, 20)];
    noProMess.textColor = SetColor(170, 170, 170, 1);
    noProMess.textAlignment = NSTextAlignmentCenter;
    noProMess.font = [UIFont systemFontOfSize:14];
    noProMess.text = @"暂无该相关产品";
    [_backTView addSubview:noProMess];
    [_tableView addSubview:_backTView];
    [self loadData];
}
- (void)loadData {
    NSString *kUrl;
//    kUrl = [NSString stringWithFormat:ProductListGGK,(NSString *)TTypeArr[_currentPage],@"10",_urlIndex];
//    if ([_urlIndex isEqualToString:@"1"]) {
//        [_dataArrayTwo removeAllObjects];
//    }
//    [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
//        NSDictionary *dic = result;
//        _totalCount = [dic objectForKey:@"totalpage"];
//        NSArray *arr = [dic objectForKey:@"prodinfo"];
//        NSLog(@"arr:%@",arr);
//        [_dataArrayTwo addObjectsFromArray:arr];
//        
//        [_tableView.header endRefreshing];
//        [_tableView.footer endRefreshing];
//        _isLoading = NO;
//        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
//            _backTView.hidden = NO;
//        }else {
//            _backTView.hidden = YES;
//        }
//        [_loading dismiss];
//        [_loading removeFromSuperview];
//        [_tableView reloadData];
//    }];
}
#pragma mark -- 点击导航栏隐藏键盘
- (void)hideKeyBoard {
    [self.view endEditing:YES];
    [_tableView endEditing:YES];
    [_tableView resignFirstResponder];
    [UIView animateWithDuration:0.2 animations:^{
        _tableView.frame = CGRectMake(0, 64 + 44, ScreenWidth, ScreenHeight-44-64 - 44);
    }];
}
#pragma mark 当键盘出现或改变时调用
-(void)keyBoardshow:(NSNotification *)notification{
    NSDictionary *info=[notification userInfo];
    NSValue *avalue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect=[self.view convertRect:[avalue CGRectValue] fromView:nil];
    double keyboardHeight=keyboardRect.size.height;//键盘的高度
    [UIView animateWithDuration:0.2 animations:^{
        _tableView.frame = CGRectMake(0, 64 + 44, ScreenWidth, ScreenHeight-keyboardHeight-44-64);
    }];
}
-(void)keyBoardhide:(NSNotification *)notification{
    [UIView animateWithDuration:0.2 animations:^{
        _tableView.frame = CGRectMake(0, 64 + 44, ScreenWidth, ScreenHeight-44-64 - 44);
    }];
}
#pragma mark -- 保存 = -= -= 
- (void)baocunBtnClick:(UIButton *)sender {
    if ([_cid isEqualToString:@""]) {
        
        [[MessShowView share]showWithMess:@"未选择商品分类"];
        return;
    }
    if (_editArr.count == 0) {
        [[MessShowView share]showWithMess:@"编辑商品为空"];
        return;
    }
    NSString *kUrl;
    /**
     *
     */
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:[AppData share].username forKey:@"productuser"];
    [dictionary setValue:_cid forKey:@"catetypeid"];
    NSMutableArray *arr = [NSMutableArray array];//产品信息
    for (int i = 0; i < _editArr.count; i++) {
        NSMutableDictionary *arrDic = [[NSMutableDictionary alloc]init];
        NSString *priceStr = (NSString *)_editArr[i][0];
        NSString *costpriceStr = (NSString *)_editArr[i][1];
        NSString *kuncunStr = (NSString *)_editArr[i][2];
        NSString *pidStr = (NSString *)_editArr[i][3];
        [arrDic setValue:pidStr forKey:@"prodid"];
        [arrDic setValue:priceStr forKey:@"price"];
        [arrDic setValue:costpriceStr forKey:@"costprice"];
        [arrDic setValue:kuncunStr forKey:@"stock"];
        [arr addObject:arrDic];
    }
    [dictionary setValue:arr forKey:@"prodinfo"];
    NSLog(@"%@",dictionary);
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
    //post请求
    kUrl = [NSString stringWithFormat:ChangeProductDataUrl];
    NSLog(@"%@",kUrl);
    NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
    [dicc setObject:dictionary forKey:@"data"];
    NSLog(@"%@",dicc);
    // 手机型号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
    // 判断是否签名
    if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
    {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
        
    }
    NSString *lower = [temUrl lowercaseString];
    if ([lower rangeOfString:@"username"].location !=NSNotFound) {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
    }
    //NSLog(@"1----------%@",temUrl);
    temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"2----------%@",temUrl);
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSError *error1;
    NSURLResponse *theResponse;
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([dic[@"r"] isEqualToString:@"T"]) {
        [[MessShowView share]showWithMess:@"添加成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [[MessShowView share]showWithMess:dic[@"m"]];
    }
}
#pragma mark--tableviewdelegate的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _editArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductLibManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"libproductcell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"ProductLibManagerCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.cancelBtn addTarget:self action:@selector(cancelBtnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    /**
     *  售价
     */
    cell.shoujiaTextF.font = [UIFont systemFontOfSize:12];
    [cell.shoujiaTextF addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];
    cell.shoujiaTextF.autocorrectionType = UITextAutocorrectionTypeNo;
    //textField.autocorrectionType=UITextAutocorrectionTypeNo;
    cell.shoujiaTextF.delegate = self;
    cell.shoujiaTextF.keyboardType = UIKeyboardTypeDecimalPad;
    
    /**
     *  成本
     */
    cell.chengbenTextF.font = [UIFont systemFontOfSize:12];
    [cell.chengbenTextF addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];
    cell.chengbenTextF.autocorrectionType = UITextAutocorrectionTypeNo;
    cell.chengbenTextF.delegate = self;
    cell.chengbenTextF.keyboardType = UIKeyboardTypeDecimalPad;
    
    /**
     *  库存
     */
    cell.kucunTextF.font = [UIFont systemFontOfSize:12];
    [cell.kucunTextF addTarget:self action:@selector(textfieldChange:) forControlEvents:UIControlEventEditingChanged];
    cell.kucunTextF.autocorrectionType = UITextAutocorrectionTypeNo;
    cell.kucunTextF.delegate = self;
    cell.kucunTextF.keyboardType = UIKeyboardTypeDecimalPad;
    
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:[_dataArrayTwo[indexPath.row] objectForKey:@"mainimage"]] placeholderImage:[UIImage imageNamed:@"product-no-pic"]];
    cell.TTitleView.text = [_dataArrayTwo[indexPath.row] objectForKey:@"productname"];
    cell.descLabel.text = [_dataArrayTwo[indexPath.row] objectForKey:@"property"];
    cell.proceLabel.text = [_dataArrayTwo[indexPath.row] objectForKey:@"price"];
    cell.shoujiaTextF.text = [_dataArrayTwo[indexPath.row] objectForKey:@"price"];
    cell.chengbenTextF.text = [_dataArrayTwo[indexPath.row] objectForKey:@"price"];
    cell.kucunTextF.text = [_dataArrayTwo[indexPath.row] objectForKey:@"dftstock"];
    
    
    return cell;
}
#pragma mark -- 选择分类btnclick--
- (void)chooseCategoryBtnClick:(UIButton *)sender {
    classifyViewController *classifyVC = [[classifyViewController alloc]init];
    classifyVC.categorySelectedBlock = ^(NSString *categoryStr,NSString *categoryId) {
        _cid = categoryId;
        _cname = categoryStr;
        CGSize size = [categoryStr sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:_chooseCateBtn.titleLabel.font,NSFontAttributeName, nil]];
        _chooseCateBtn.frame = CGRectMake(ScreenWidth - 20 - size.width, 0, size.width, 44);
        [_chooseCateBtn setTitle:categoryStr forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:classifyVC animated:YES];
}
#pragma mark -- 取消按钮点击--
- (void)cancelBtnClick:(UIButton *)sender event:(id)event{
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_tableView];
    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
    [_dataArrayTwo removeObjectAtIndex:indexPath.row];
    [_editArr removeObjectAtIndex:indexPath.row];
    
    if (_editArr.count == 0) {
        _backTView.hidden = NO;
    }else {
        _backTView.hidden = YES;
    }
    [_tableView reloadData];
}
//#pragma mark -- 去textfield所在的cell
//- (void)textFieldDidBeginEditing:(UITextField *)textField {
//    if (textField.tag == 2222 || textField.tag == 2223) {
//        if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0) {
//            UIView *v = [textField superview];
//            UIView *vv = [v superview];
//            UIView *vvv = [vv superview];
//            NSLog(@"%f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
//            ProductLibManagerCell *cell = (ProductLibManagerCell *)[vvv superview];
//            NSIndexPath *indexpath = [_tableView indexPathForCell:cell];
//            _indexPath = indexpath;
//        }else {
//            UIView *v = [textField superview];
//            UIView *vv = [v superview];
//            ProductLibManagerCell *cell = (ProductLibManagerCell *)[vv superview];
//            NSIndexPath *indexpath = [_tableView indexPathForCell:cell];
//            _indexPath = indexpath;
//        }
//    }
//}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 900 || textField.tag == 901 || textField.tag == 902) {
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0) {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            UIView *vvv = [vv superview];
            NSLog(@"%f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
            ProductLibManagerCell *cell = (ProductLibManagerCell *)[vvv superview];
            NSIndexPath *indexpath = [_tableView indexPathForCell:cell];
            _indexPath = indexpath;
        }else {
            UIView *v = [textField superview];
            UIView *vv = [v superview];
            ProductLibManagerCell *cell = (ProductLibManagerCell *)[vv superview];
            NSIndexPath *indexpath = [_tableView indexPathForCell:cell];
            _indexPath = indexpath;
        }
        NSString *pid = [_dataArrayTwo[_indexPath.row] objectForKey:@"prodid"];
        NSMutableArray *arr = [NSMutableArray array];
        NSString *shoujiaStr;
        NSString *chengbenStr;
        NSString *kuncunStr;
        if ([_shoujiaStr isEqualToString:@""]) {
            shoujiaStr = [_dataArrayTwo[_indexPath.row] objectForKey:@"price"];
        }else {
            shoujiaStr = _shoujiaStr;
        }
        if ([_chengbenStr isEqualToString:@""]) {
            chengbenStr = [_dataArrayTwo[_indexPath.row] objectForKey:@"price"];
        }else {
            chengbenStr = _chengbenStr;
        }
        if ([_kucunStr isEqualToString:@""]) {
            kuncunStr = [_dataArrayTwo[_indexPath.row] objectForKey:@"dftstock"];
        }else {
            kuncunStr = _kucunStr;
        }
        [arr addObject:shoujiaStr];
        [arr addObject:chengbenStr];
        [arr addObject:kuncunStr];
        [arr addObject:pid];
        [_editArr replaceObjectAtIndex:_indexPath.row withObject:arr];
    }
}
#pragma mark -- 词频所有词变更判断
- (void)textfieldChange:(UITextField *)textField {
    NSLog(@"1234567890-");
    if (textField.tag == 900) {
        if ([self validateNumber:textField.text]) {
            _shoujiaStr = textField.text;
        }else {
            textField.text = _shoujiaStr;
        }
    }else if (textField.tag == 901){
        if ([self validateNumber:textField.text]) {
            _chengbenStr = textField.text;
        }else {
            textField.text = _chengbenStr;
        }
    }else if (textField.tag == 902){
        if ([self validateNumber:textField.text]) {
            _kucunStr = textField.text;
        }else {
            textField.text = _kucunStr;
        }
    }
}
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //if (textField == _textField1) {
    NSScanner      *scanner    = [NSScanner scannerWithString:string];
    NSCharacterSet *numbers;
    NSRange         pointRange = [textField.text rangeOfString:@"."];
    
    if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
    {
        numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    }
    else
    {
//        if (textField == _textField1) {
//            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
//        }else {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
//        }
    }
    
    if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
    {
        return NO;
    }
    
    short remain = 2; //默认保留2位小数
    
    NSString *tempStr = [textField.text stringByAppendingString:string];
    NSUInteger strlen = [tempStr length];
    if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
        if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
            return NO;
        }
        if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
            return NO;
        }
    }
    NSRange zeroRange = [textField.text rangeOfString:@"0"];
    if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
        if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
            textField.text = string;
            return NO;
        }else{
            if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                if([string isEqualToString:@"0"]){
                    return NO;
                }
            }
        }
    }
    NSString *buffer;
    if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
    {
        return NO;
    }
    //}
    return YES;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0001;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self hideKeyBoard];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
